import Taro from '@tarojs/taro'
import appConfig from './appConfig';
import { getUserStore } from '@/common/hox/userStore'
import { getNetworkStore } from '@/common/hox/networkStore'

// if (process.env.TARO_ENV === 'h5') {
//     Taro?.addInterceptor(Taro.interceptors.timeoutInterceptor)
// }

async function request<T = any>(data: Record<string, any> | string): Promise<T> {
    let URL = appConfig.baseUrl;
    let merchantId = appConfig.merchantId;
    let param = {
        url: appConfig.baseUrl || '',
        timeout: 10 * 1000,
        header: {
            merchantId: merchantId ? merchantId : appConfig.businessMerchantAppConfigId,
            appPlatformType: appConfig?.appPlatformType,
            businessMerchantAppConfigId: appConfig.businessMerchantAppConfigId,
            // 'content-type':'application/json',
            // businessToken,
        }
    }

    if (typeof data === 'object') {
        data.url = data.url.includes('http') ? data.url : `${URL}${data.url}`
        param = {
            ...param,
            ...data
        }
    }
    if (typeof data === 'string') {
        data = data.includes('http') ? data : `${URL}${data}`
        param = {
            ...param,
            url: data
        }
    }

    const token = getUserStore()?.token
    if (token) {
        const tokenBearer = { Authorization: `Bearer ${token}` }
        param.header = {
            ...param.header,
            ...tokenBearer
        }
    }
    // 重授权
    const error403 = async () => {
        Taro.reLaunch({ url: '/pages/index/index' })
        throw new Error('授权过期')
    }

    // 登录过期
    const error401 = async () => {
        // const { clear } = getUserStore()
        // clear?.()
        Taro.showModal({
            title: '提示',
            content: '未登录或登录已过期，请重新登录',
            showCancel: false,
            success: (res) => {
                if (res.confirm) {
                    if (process.env.TARO_ENV === 'h5') {
                        // H5 环境登录信息失效 逻辑
                    }
                    else {
                        // 其他环境登录信息失效 逻辑
                    }
                }
            }
        })
    }

    // 根据浏览器返回错误code码 展示对应提示
    const errorCode = async (code) => {
        if (!code || code == 404) return;
        Taro.showModal({
            title: '提示',
            content: '系统异常，请稍后重试，错误码：' + code,
            confirmText: '关闭',
            showCancel: false
        });
        throw new Error('系统异常')
    }

    const weakNetworkTimeout = getNetworkStore()?.requestWeak()
    return Taro.request(param).then(async res => {
        if (res.header.newtoken) getUserStore()?.setToken(res.header.newtoken)
        if (res.statusCode == 403 || res.data.code == 403) return await error403()
        if (res.statusCode == 401 || res.data.code == 401 || res.data.code == '401') return await error401()
        if (res.statusCode !== 200) return await errorCode(res.statusCode)
        if (res.data.code !== '0' && res.data.message) {
            Taro.hideLoading()
            if (res.data.message === '缺失推广参数') {
                return;
            }

            if (param.url.includes('api/CouponActivity/CollectDistribute')) {
                Taro.showModal({
                    title: '',
                    content: res.data.message,
                    showCancel: false,
                    confirmText: '我知道了'
                })
                throw new Error(res.data.code)
            }

            if (res.data.code == '311') {
                return Taro.showModal({
                    title: '提示',
                    content: res.data.message,
                    showCancel: false,
                    success: () => {
                        Taro.reLaunch({ url: '/pages/index/index' })
                    }
                })
            }

            Taro.showModal({
                title: '提示',
                content: res.data.message,
                confirmText: '关闭',
                showCancel: false
            })
            
            throw new Error(res.data.code)
        }

        // 兼容一些后端返回可能不规范的问题
        return res.data.data !== null && res.data.data !== undefined ? res.data.data : res.data
    }).catch((res) => {
        if (res.statusCode == 403 || res.status == 403) return error403()
        if (res.statusCode == 401 || res.status == 401) return error401()
        if (res.statusCode !== 200) {
            if (process.env.TARO_ENV === 'weapp') {
                // 超时判断
                if (res.errno === 5) {
                    getNetworkStore()?.requestTimeout()
                    return
                }
                // 无网判断
                if (res.errno === 600001) {
                    getNetworkStore()?.setUnAvailable()
                    return
                }
            }
            if (process.env.TARO_ENV === 'h5') {
                if (res.message === '网络链接超时,请稍后再试！') {
                    getNetworkStore()?.requestTimeout()
                    return
                }
            }
            errorCode(res.statusCode)
            return
        }
    }).finally(() => {
        weakNetworkTimeout && clearTimeout(weakNetworkTimeout)
    })



}

request.get = (url: string, data?: { params: Record<any, any> }) => request({
    url,
    data: data?.params,
    method: 'GET'
})
request.post = (url: string, data?: Record<any, any>) => request({
    url,
    data: data,
    method: 'POST'
})

export default request
